﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Simple.Services.System;
using Simple.Services.System.FileInfo;

namespace Simple.Services
{
    public class CourseService : BusinessBaseService
    {
        private readonly SimpleDbContext _context;
        private readonly FileInfoService _fileInfoService;
        public CourseService(SimpleDbContext context,
            ISimpleService services,
            FileInfoService fileInfoService) : base(services)
        {
            _context = context;
            _fileInfoService = fileInfoService;
        }

        public async Task<List<CourseModel>> GetAsync()
        {
            var lstCourse = await (await OrganizationFilter(_context.Set<Course>())).ToListAsync();
            return MapperHelper.Map<List<CourseModel>>(lstCourse);
        }

        public async Task<PageResultModel<CourseModel>> GetPageAsync(CoursePageInputModel input)
        {
            var result = new PageResultModel<CourseModel>();
            var query = await OrganizationFilter(_context.Set<Course>().Include(p => p.CourseType).Include(p => p.Lecturer).AsQueryable());

            // 根据条件查询
            if (!string.IsNullOrEmpty(input.Name))
            {
                query = query.Where(u => u.CourseName.Contains(input.Name));
            }

            // 获取总数量
            result.TotalRows = await query.CountAsync();

            // 分页查询
            query = query.OrderBy(u => u.CreatedTime).Page(input.PageNo, input.PageSize);
            var lstCourse = await query.ToListAsync();
            var lstCourseDto = MapperHelper.Map<List<CourseModel>>(lstCourse);
            var lstImgId = lstCourseDto.Select(p => p.ImgId).ToList();

            foreach (var item in lstCourseDto)
            {

            }

            result.Rows = lstCourseDto;

            result.SetPage(input);
            result.CountTotalPage();

            return result;
        }

        public async Task<int> AddAsync(CourseInputModel model)
        {
            var course = MapperHelper.Map<Course>(model);
            var fileId = (await _fileInfoService.BusinessUploadAsync(new List<IFormFile>() { model.File }, FileSource.Course, string.Empty)).FirstOrDefault();
            if (fileId != Guid.Empty)
            {
                course.ImgId = fileId.ToString();
            }
            var entityChild = await _context.AddAsync(course);

            return await _context.SaveChangesAsync();
        }

        public async Task<int> UpdateAsync(CourseInputModel model)
        {
            var course = await _context.Set<Course>()
                .Where(u => model.Id == u.Id)
                .FirstOrDefaultAsync();

            if (course == null)
            {
                throw AppResultException.Status404NotFound("找不到课程，更新失败");
            }
            if (model.File != null)
            {
                var fileId = (await _fileInfoService.BusinessUploadAsync(new List<IFormFile>() { model.File }, FileSource.Course, string.Empty)).FirstOrDefault();
                if (fileId != Guid.Empty)
                {
                    course.ImgId = fileId.ToString();
                }
            }
            MapperHelper.Map(model, course);

            var entityChild = _context.Update(course);
            int ret = await _context.SaveChangesAsync();

            if (ret == 0)
            {
                throw AppResultException.Status200OK("更新记录数为0");
            }
            return ret;
        }

        public async Task<int> DeleteAsync(IEnumerable<Guid> ids)
        {
            var lstCourse = await _context.Set<Course>()
                .Where(u => ids.Contains(u.Id))
                .ToListAsync();

            _context.RemoveRange(lstCourse);
            return await _context.SaveChangesAsync();
        }

        public async Task<int> ChangeEnable(ChangeEnableDto input)
        {
            var course = await _context.Set<Course>()
                .Where(u => input.Id == u.Id)
                .FirstOrDefaultAsync();

            if (course == null)
            {
                throw AppResultException.Status404NotFound("找不到课程，更新失败");
            }
            course.IsEnable = input.IsEnable;
            _context.Update(course);
            return await _context.SaveChangesAsync();
        }

        public async Task<int> Play(Guid id)
        {
            var course = await _context.Set<Course>()
                    .Where(u => u.Id == id)
                    .FirstOrDefaultAsync();

            if (course == null)
            {
                throw AppResultException.Status404NotFound("找不到课程，更新失败");
            }
            course.PlayCount = course.PlayCount == null ? 1 : course.PlayCount+1;
            _context.Update(course);
            return await _context.SaveChangesAsync();
        }

        #region 移动端
        public async Task<PageResultModel<MobileCourseModel>> GetMobilePageAsync(MobileCoursePageInputModel input)
        {
            var result = new PageResultModel<MobileCourseModel>();
            var query = await OrganizationFilter(_context.Set<Course>().Include(p => p.CourseType).Include(p => p.Lecturer).AsQueryable());

            // 根据条件查询
            if (input.CourseTypeId.HasValue)
            {
                query = query.Where(u => u.CourseTypeId == input.CourseTypeId);
            }

            // 获取总数量
            result.TotalRows = await query.CountAsync();

            // 分页查询
            query = query.OrderBy(u => u.CreatedTime).Page(input.PageNo, input.PageSize);
            var lstCourse = await query.ToListAsync();
            var lstCourseDto = MapperHelper.Map<List<MobileCourseModel>>(lstCourse);
            var lstImgId = lstCourseDto.Select(p => p.ImgId).ToList();

            foreach (var item in lstCourseDto)
            {

            }

            result.Rows = lstCourseDto;

            result.SetPage(input);
            result.CountTotalPage();

            return result;
        }
        #endregion
    }


}
